<!-- 任务再委托 -->
<template>
  <view>
    <u-sticky>
      <u-tabs
        class="tabs"
        :list="tabsList"
        @click="onTabClick"
        :scrollable="false"
        style="padding: 0 24rpx; background: #fff; z-index: 22; position: sticky; top: 0px"
        :activeStyle="{ color: '#171717', fontSize: '14px' }"
        :inactiveStyle="{ color: '#C6C6C6', fontSize: '14px' }"
        lineColor="#1E6FFF"
      ></u-tabs>
    </u-sticky>
    <view class="task_lists" :style="{ paddingBottom: tabvalue == '待办' ? '130rpx' : '0' }">
      <collapse name="基本信息" id="outside1" :maxHeight="maxHeight">
        <view class="listdefault" :id="uId">
          <view class="action" v-for="(item, key) in basicInfo" :key="key">
            <view class="list1">{{ key }}</view>
            <view class="list2">{{ detailData[item] }}</view>
          </view>
        </view>
      </collapse>
      <collapse name="项目信息" id="outside2" :maxHeight="maxHeight1">
        <view class="listdefault" :id="uId1">
          <view class="action" v-for="(item, key) in projectInfo" :key="key">
            <template>
              <view class="list1">{{ key }}</view>
              <view class="list2">{{ detailData[item] }}</view>
            </template>
          </view>
        </view>
      </collapse>
      <collapse name="需分配任务信息" id="outside4" :maxHeight="maxHeight2">
        <view class="listdefault" :id="uId2">
          <view class="action" v-for="(item, key) in taskInfo" :key="key">
            <template>
              <view class="list1">{{ key }}</view>
              <view class="list2">{{ detailData[item] }}</view>
            </template>
          </view>
        </view>
      </collapse>
      <u-collapse :value="['task']" ref="taskCollapse">
        <u-collapse-item title="新增分配任务信息" name="task">
          <view class="listdefault" v-for="(entity, index) in redistributionDtList" :key="index">
            <view class="action" v-for="(item, key) in taskItemFields" :key="key">
              <view class="list1">{{ key }}</view>
              <view class="list2">{{ entity[item] }}</view>
            </view>
          </view>
        </u-collapse-item>
      </u-collapse>
			<!-- <u-collapse :value="['taskPayment']" ref="taskPaymentCollapse">
			  <u-collapse-item title="需分配款项信息" name="taskPayment">
			    <view class="listdefault" v-for="(entity, index) in receivablePaymentList" :key="index">
			      <view class="action" v-for="(item, key) in taskPaymentItemFields" :key="key">
			        <view class="list1">{{ key }}</view>
			        <view class="list2">{{ entity[item] }}</view>
			      </view>
			    </view>
			  </u-collapse-item>
			</u-collapse> -->
			<action-collapse name="需分配款项信息" :childFields="taskPaymentItemFields" id="taskPayment" :dataSource="receivablePaymentList"></action-collapse>
      <default-list name="项目信息附件">
        <file-list :fileList="detailData.attachment"></file-list>
      </default-list>
      <default-list name="需分配任务附件">
        <file-list :fileList="detailData.file"></file-list>
      </default-list>
      <default-list name="流程图" id="outside3">
        <template slot="right">
          <view class="flow_right" @click="flowView">
            <image src="../../static/synergy/viewflow.png" mode="aspectFill"></image>
            <text>流程图</text>
          </view>
        </template>
        <flow-list :dataSource="resultList"></flow-list>
      </default-list>
    </view>
    <view class="task_bottom" v-if="tabvalue == '待办'">
      <view class="task_bottom_write" @click="approval">
        <image src="../../static/synergy/write_commont.png" mode="aspectFill"></image>
        <text>审批</text>
      </view>
      <view class="refuse" @click="refuseProcess" v-if="nodeObj.isSubmit !== '1'">退回</view>
      <view
        class="agree"
        @click="agreeProcess"
        :style="{ flex: nodeObj.isSubmit == '1' ? 1 : 'initial', margin: nodeObj.isSubmit == '1' ? '0 20rpx' : '' }"
      >
        同意
      </view>
    </view>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>
<script>
import actionCollapse from './components/actionCollapse.vue'
import http from '@/utils/request'
import detailInformationList from './components/detailInformationList.vue'
import fileList from './components/fileList.vue'
import collapse from './components/collapse.vue'
import defaultList from './components/defaultList.vue'
import flowList from './components/flowList.vue'
import address from '@/utils/address.js'
import { filterMultiDictText, initDictOptions } from '@/utils/JDictSelectUtil.js'
import {
  erpOmcTaskDistributionDtQueryById,
  erpOmcTaskDistributionDtChildTable, //  任务子表
  erpProjectReportPaybackDisclaimerDisclaimerInfoList, // 免责信息子表
  erpOmcProjectId, // 获取项目详情
  getProcessTaskTransInfo, // 查询流程流转信息
  getProcessHistoryList, // 查询流程图信息
  getNodePositionInfo, // 查询坐标信息数据
  rejectProcess, // 退回
  processComplete, // 提交完成
  // getChildrenListCarMaintenance, //子表
} from '@/api/index.js'
import { BASE_URL } from '@/utils/baseUrl.js'
export default {
  data() {
    return {
      address,
      filterMultiDictText,
      tabsList: [
        { name: '基本信息', id: 'outside1' },
        { name: '流程', id: 'outside3' },
      ],
      childTable: [],
      redistributionDtList: [],
			receivablePaymentList: [], // 需分配款项信息
      detailData: {}, // 详情数据
      dictOptions: {}, // 详情数据
      basicInfo: {
        // 标题: 'bpmBizTitle',
        单据编号: 'billNo',
        申请时间: 'createTime',
        申请人: 'handlerId_dictText',
        申请部门: 'handlerDeptId_dictText',
      },
      projectInfo: {
        项目名称: 'projectName',
        项目编号: 'finalNo',
        经营团队: 'teamName_dictText',
        项目承接人: 'undertaker_dictText',
        立项日期: 'projectEstablishDate',
        签订单位: 'signUnit_dictText',
        业绩归属年度: 'year',
        业主单位: 'ownerUnit_dictText',
        联系人: 'contacts_dictText',
        联系方式: 'contactTel',
        项目所在地址: 'addressDetail',
        项目详细地址: 'projectAddress',
        项目来源: 'projectSource_dictText',
        '预计合同额(元)': 'estimatedContractAmount',
        预计合同额大写: 'estimatedContractcapitalChineseAmount',
        立项事由及说明: 'establishReason',
      },
      taskInfo: {
        任务编号: 'taskNo',
        业务分类: 'categoryName',
        '合同占比(%)': 'contractRate',
        '合同分配额(元)': 'contractAmount',
        '切割合同额（元)': 'cutContractAmount',
        生产团队: 'productTeam_dictText',
        '需分配合同额(元)': 'separateContractAmount',
        '需分配切割合同额(元)': 'needCutContractAmount',
        是否作废: 'isCancel_dictText',
        说明: 'reason',
      },
      taskItemFields: {
        // 子表字段
        业务分类: 'categoryName',
        '合同占比（%）': 'contractRate',
        '合同分配额（元)': 'contractAmount',
        '切割合同额（元)': 'cutContractAmount',
        生产团队: 'productTeam_dictText',
        // 生产公司: 'productCompanyId_dictText',
      },
			taskPaymentItemFields: {
        '款项名称': 'paymentName',
        '款项节点说明': 'paymentDesc',
        '款项关联任务': 'taskId_dictText',
        '需分配款项金额(元)': 'isAllowDistributionMoney',
        '应收状态': 'shouldPayFlag_dictText',
      },
			
      childFields: {
        // 子表字段
        款项名称: 'paymentName',
        应收款金额: 'amountReceivable',
        豁免类型: 'exemptionType',
        豁免对象: 'exemptionManagementTeam',
        豁免考核月份: 'exemptionDateBegin',
        豁免罚款金额: 'exemptionPenaltyAmount',
      },
      resultList: [], // 流程图数据
      nodePositionInfo: {}, // 坐标信息
      processInstanceId: '',
      scrollTop: 0, // 滚动顶部距离
      model: {}, // 处理单据表信息
      resultObj: {}, // 流程图流转信息
      nodeObj: {}, // 流程节点信息
      tabvalue: '', // 协同首页tabs name
      // childSource: [], // 字表数据
      isClick: false,
      maxHeight: 0,
      maxHeight1: 0,
      maxHeight2: 0,
      uId: uni.$u.guid(),
      uId1: uni.$u.guid(),
      uId2: uni.$u.guid(),
    }
  },
  components: {
    actionCollapse,
    detailInformationList,
    fileList,
    collapse,
    defaultList,
    flowList,
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop
  },
  onReady() {
    uni.setNavigationBarTitle({
      title: this.model.bpmBizTitle.replace(/(【|】)/g, ''),
    })
  },
  onLoad(options) {
    this.model = JSON.parse(decodeURIComponent(options.item))
    var that = this
    // #ifdef APP-NVUE
    var eventChannel = this.$scope.eventChannel // 兼容APP-NVUE
    // #endif
    // #ifndef APP-NVUE
    var eventChannel = this.getOpenerEventChannel()
    // #endif
    // 监听sendMessage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('sendMessage', function (data) {
      that.tabvalue = data.tabvalue
      that.nodeObj = JSON.parse(decodeURIComponent(data.nodeObj))
      that.getNodePositionInfoData(that.model.processInstanceId)
      if (this.tabvalue == '待办') {
        that.getProcessTaskTrans(that.model.id)
      }
      // that.initDictConfig()
      Promise.allSettled([that.loadData(that.nodeObj.dataId), that.initDictConfig(), that.getChildTable()]).then(() => {
        that.$nextTick(() => {
          that.$refs.taskCollapse.init()
        })
      })
    })
  },
  methods: {
    getExemptionObject(record, key, item) {
      if (record.exemptionType === '1') {
        return filterMultiDictText(this.dictOptions['teamId'], record.exemptionManagementTeam + '')
      }
      if (record.exemptionType === '2') {
        return filterMultiDictText(this.dictOptions['empId'], record.exemptionUndertaker + '')
      }
      if (record.exemptionType === '3') {
        return record.exemptionProjectHead
      }
      return ''
    },
    initDictConfig() {
      return Promise.allSettled([
        initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'teamId', res.result)
          }
        }),
        initDictOptions('erp_omc_project_task,category_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'categoryName', res.result)
          }
        }),
        initDictOptions('erp_employee_file,name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'empId', res.result)
          }
        }),
        //款项名称
        initDictOptions('erp_progress_payment_node,node_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'paymentName', res.result)
          }
        }),
        //豁免类型
        initDictOptions('exemption_type').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'exemptionType', res.result)
          }
        }),
      ])
    },
    getChildTable() {
      return erpOmcTaskDistributionDtChildTable({
        pageNo: 1,
        pageSize: 100,
        mainId: this.nodeObj.dataId,
        column: 'createTime',
        order: 'desc',
        field: 'id',
      })
        .then((response) => {
          this.redistributionDtList = response.result || []
        })
    },
    // 点击进入审批页面
    approval() {
      if (this.isClick) {
        return
      }
      var that = this
      var nextnode = ''
      if (this.resultObj.transitionList) {
        this.resultObj.transitionList.forEach((item) => {
          nextnode += ',' + item.nextnode
        })
      }
      uni.navigateTo({
        url: '/pages/synergy/approval',
        success: function (res) {
          // 通过eventChannel向被打开页面传送数据
          res.eventChannel.emit('acceptDataFromOpenerPage', {
            nodeObj: encodeURIComponent(JSON.stringify(that.nodeObj).replace(/%/g, '%25')),
            model: encodeURIComponent(JSON.stringify(that.model).replace(/%/g, '%25')),
            nextnode: nextnode,
          })
        },
      })
    },
    // 查询流程流转信息 -- 获取下一节点信息
    getProcessTaskTrans(taskId) {
      getProcessTaskTransInfo({ taskId })
        .then((res) => {
          if (res.success) {
            this.resultObj = res.result
          } else {
            this.$refs.uToast.show({
              message: res.message,
              type: 'error',
            })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 查询详情
    loadData(id) {
      return erpOmcTaskDistributionDtQueryById({ id }).then(async (res) => {
        if (res.success) {
          this.detailData = await res.result
					this.getReceivablePayment()
          this.projectNumber(res.result.projectId)
          this.taskNumber(res.result.taskId)
          var arr = await res.result.areaCode.split(',')
          var addressDetail = await ''
          this.address.map((value) => {
            if (arr[0] && value.code == arr[0]) {
              addressDetail = value.name
              value.children.map((val) => {
                if (arr[1] && val.code == arr[1]) {
                  addressDetail = addressDetail + val.name
                  val.children.map((item) => {
                    if (arr[2] && item.code == arr[2]) {
                      addressDetail = addressDetail + item.name
                    }
                  })
                }
              })
            }
          })
          this.detailData.addressDetail = addressDetail
          this.timer = setTimeout(() => {
            this.$nextTick(() => {
              ['uId', 'uId1', 'uId2'].forEach((uid, index) => {
                uni
                  .createSelectorQuery()
                  .select('#' + this[uid])
                  .boundingClientRect((data) => {
                    this[`maxHeight${index || ''}`] = data.height
                  })
                  .exec()
              })
            })
            clearTimeout(this.timer)
            this.timer = null
          }, 300)
          // this.getChildData(this.detailData.id)
        } else {
          this.$refs.uToast.show({
            message: res.message,
            type: 'error',
          })
        }
      })
    },
		getReceivablePayment () {
			http.get('/api/erp/task/erpOmcTaskRedistribution/queryReceivablePayment', {
			  taskId: this.detailData.taskId,
			  mainId: this.detailData.id,
				type: '2'
			}).then((res) => {
				if (res.result && res.result.length > 0) {
					res.result.map((value, index) => {
						res.result[index].shouldPayFlag_dictText = value.shouldPayFlag && value.shouldPayFlag == '1' ? '已生成' : '未生成'
						res.result[index].taskId_dictText = '' // 首先款项关联任务字段默认为空
						// 遍历planTaskList数组赋值给taskId_dictText
						res.result[index].taskId_dictText = value.planTaskVoList && value.planTaskVoList.length ? (value.planTaskVoList.map((obj) => { return obj.categoryName }).join(',')) : '';
					})
					this.receivablePaymentList = res.result
				} else {
					this.receivablePaymentList = []
				}
			  this.receivablePaymentList = res.result
			})
		},
    // 获取项目编号
    projectNumber(projectId) {
      erpOmcProjectId({ id: projectId }).then((res) => {
        if (res.success) {
          this.$set(this.detailData, 'finalNo', res.result.finalNo) // 项目编号
        } else {
          this.$refs.uToast.show({
            message: res.message,
            type: 'error',
          })
        }
      })
    },
    // 获取任务编号
		taskNumber(taskId) {
		  http.get('/api/erp/omc/project/erpOmcProjectTask/queryById', { id: taskId }).then((res) => {
		    if (res.success) {
		      var event = res.result
		      this.$set(this.detailData, 'taskNo', event.billNo?event.billNo: taskId) // 任务编号
		    } else {
					this.$set(this.detailData, 'taskNo', taskId) // 任务编号
		      this.$refs.uToast.show({
		        message: res.message,
		        type: 'error',
		      })
		    }
		  }).catch(err => {
				this.$set(this.detailData, 'taskNo', taskId) // 任务编号
			})
		},
    // 查询流程节点信息 -- 流程图数据
    getProcessHistoryListS(processInstanceId) {
      var url = ''
      var params = ''
      url = getProcessHistoryList
      params = {
        processInstanceId: processInstanceId,
      }

      url(params).then((res) => {
        if (res.success) {
          this.resultList = res.result.records
        } else {
          this.$refs.uToast.show({
            message: res.message,
            type: 'error',
          })
        }
      })
    },
    // 查询坐标信息数据 -- 流程图备注
    getNodePositionInfoData(processInstanceId) {
      getNodePositionInfo({ processInstanceId })
        .then((res) => {
          if (res.success) {
            this.nodePositionInfo = res.result
            this.getProcessHistoryListS(processInstanceId)
          } else {
            this.$refs.uToast.show({
              message: res.message,
              type: 'error',
            })
          }
        })
        .catch((e) => {
          console.error(e)
        })
    },
    // 流程图预览
    flowView() {
      var params = `_t=${Date.parse(new Date()) / 1000}&processInstanceId=${this.model.processInstanceId}`
      var url = `${BASE_URL}/api/erpmng/act/task/traceImage?${params}`
      this.viewImage(url)
    },
    // 预览图片
    viewImage(url) {
      uni.previewImage({
        urls: [url],
        longPressActions: {
          itemList: ['保存图片'],
          success: function (data) {
            uni.downloadFile({
              url: url,
              success: (result) => {
                if (result.statusCode === 200) {
                  //文件保存到本地
                  uni.saveFile({
                    tempFilePath: result.tempFilePath, //临时路径
                    success: function (ress) {
                      uni.showToast({
                        icon: 'none',
                        mask: true,
                        title: '文件已保存：' + ress.savedFilePath, //保存路径
                        duration: 3000,
                      })
                    },
                  })
                }
              },
              fail: (err) => {
                uni.showToast({
                  icon: 'none',
                  mask: true,
                  title: '失败请重新下载',
                })
              },
            })
          },
          fail: function (err) {
            console.log(err.errMsg)
          },
        },
      })
    },
    // 点击tabs
    onTabClick(item) {
      uni
        .createSelectorQuery()
        .in(this)
        .select(`#${item.id}`)
        .boundingClientRect((data) => {
          uni.pageScrollTo({
            scrollTop: data.top + this.scrollTop - 54,
            duration: 150,
          })
        })
        .exec()
    },
    // 拒绝流程
    refuseProcess() {
			var that = this
			var nextnode = ''
			if(this.resultObj.transitionList){
				this.resultObj.transitionList.forEach(item => {
					nextnode += ',' + item.nextnode
				})
			}
			uni.navigateTo({
				url:'/pages/synergy/approval',
				success: function(res) {
					// 通过eventChannel向被打开页面传送数据
					res.eventChannel.emit('acceptDataFromOpenerPage', {
						nodeObj: encodeURIComponent(JSON.stringify(that.nodeObj).replace(/%/g, '%25')),
						model: encodeURIComponent(JSON.stringify(that.model).replace(/%/g, '%25')),
						resultObj: encodeURIComponent(JSON.stringify(that.resultObj).replace(/%/g, '%25')),
						nextnode: nextnode,
						noAgree: '1'
						
					})
				}
			})
		},
    // 同意流程
    agreeProcess() {
      if (this.isClick) {
        this.$refs.uToast.show({
          message: '请勿重复点击！',
          type: 'default',
        })
        return
      }
      var nextnode = ''
      if (this.resultObj.transitionList) {
        this.resultObj.transitionList.forEach((item) => {
          nextnode += ',' + item.nextnode
        })
      }
      this.isClick = true

      var _this = this
      uni.showModal({
        content: '该任务将同意审批，是否继续？',
        cancelText: '否',
        confirmText: '是',
        confirmColor: '#576B95',
        cancelColor: '#000000',
        success: function (res) {
          if (res.confirm) {
            var params = {
              bizTaskList: '[]',
              ccUserIds: '',
              ccUserRealNames: '',
              fileList: '[]',
              isSubmit: _this.nodeObj.isSubmit,
              method: 'post',
              nextCodeCount: '',
              nextUserId: '',
              nextUserName: '',
              nextnode: nextnode ? nextnode.substring(1) : '',
              procInsId: _this.model.processInstanceId,
              processModel: 1,
              reason: '同意',
              rejectModelNode: '',
              taskId: _this.model.id,
            }
            processComplete(params)
              .then((res) => {
                _this.$refs.uToast.show({
                  message: res.message,
                  type: res.success ? 'success' : 'error',
                  duration: 1000,
                  complete() {
                    if (res.success) uni.navigateBack()
                    _this.isClick = false
                  },
                })
              })
              .catch((err) => {
                _this.isClick = false
              })
          } else if (res.cancel) {
            _this.show = false
            _this.isClick = false
          }
        },
      })
    },
  },
}
</script>
<style lang="scss" scoped>
@import './common/action.scss';
.task_lists {
  padding: 20rpx 20rpx 0;
}
.image_lists {
  padding: 0 0 12rpx 12rpx;
  display: flex;
  flex-wrap: wrap;
  .image_list {
    margin-bottom: 20rpx;
    width: 144rpx;
    margin-right: 14rpx;
    .image_img {
      width: 116rpx;
      height: 116rpx;
      padding: 12rpx;
      background: rgba(0, 0, 0, 0.02);
      border-radius: 1px;
      border: 1px solid rgba(0, 0, 0, 0.08);
      position: relative;
      .image_action {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translateX(-50%) translateY(-50%);
        width: 36rpx;
        height: 36rpx;
      }
      .image_source {
        width: 100%;
        height: 100%;
      }
    }
    .image_name {
      font-size: 20rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #b2b2b2;
      line-height: 28rpx;
      margin-top: 8rpx;
      text-align: left;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      width: 152rpx;
    }
  }
}

.flow_right {
  display: flex;
  align-items: center;
  image {
    width: 40rpx;
    height: 40rpx;
  }
  text {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #1e6fff;
    line-height: 40rpx;
    margin-left: 4rpx;
  }
}

.task_bottom {
  display: flex;
  align-items: center;
  padding: 20rpx 0 20rpx 52rpx;
  background-color: #ffffff;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 10000;
  .task_bottom_write {
    display: flex;
    align-items: center;
    image {
      width: 48rpx;
      height: 48rpx;
      margin-right: 8rpx;
    }
    text {
      font-size: 28rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #7f7f7f;
      line-height: 40rpx;
    }
  }
  .refuse {
    width: 168rpx;
    height: 90rpx;
    line-height: 90rpx;
    background: rgba(0, 0, 0, 0.05);
    border-radius: 10rpx;
    margin: 0 16rpx 0 52rpx;
    font-size: 34rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.5);
    text-align: center;
  }
  .agree {
    width: 318rpx;
    height: 90rpx;
    line-height: 90rpx;
    background: #1e6fff;
    border-radius: 10rpx;
    font-size: 34rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #ffffff;
    text-align: center;
  }
}
</style>
